<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品详情页面-web0701</title>
    <link rel="stylesheet/less" href="./css/item.less">
</head>

<body>

    <div id="box">
        <SCript type="text/html" id="box-template">
            <h2 class="title">商品的详细页面</h2>
            <div class="img">
                <img src="{{IMAGE1}}" alt="">
            </div>
            <p class="name">{{NAME}}</p>
            <p class="oldPrice">{{ORI_PRICE}}</p>
            <p class="nowRPrice">{{PRESENT_PRICE}}</p>
            <div>
                {{#DETAIL}}
            </div>
        </SCript>


    </div>
    <div class="btn">
        <button id="addCart">添加购物车</button>
        <button onclick="javascript:history.back()">返回</button>
    </div>

    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/art-template/4.13.2/lib/template-web.js">
    </script>
    <script src="https://cdn.bootcdn.net/ajax/libs/less.js/2.5.3/less.js"></script>
    <script type="module">

        import $$ from "./common/js/myTools.js"
        const {getNode,baseURL} = $$
        const cartBtnNode = getNode("#addCart")

        // 获取商品id 
        window.id = location.hash.substr(1)
    

        async function loadItem() {

            window.goods = await $$.myAjax({
               url:"http://localhost:3000/goods/"+id,
               dataType:"json"
           })
          
           const html =   template("box-template",goods)
           const boxNode = getNode("#box")
           boxNode.innerHTML = html;
           

        }

        loadItem();
  
        cartBtnNode.onclick = function() {
            // 1  判断原来的购物车是否存在该商品 
           const carts = $$.getCookie("cart") || []

           //  2 判断是否存在 
           const flag  = carts.some(cart => cart.id === id)

           if(flag) {
               // 存在   提示  跳转到购物车页面 
               alert("当前购物车中已有该商品.....")
           }else {
               // 获取当前商品的主要信息
               const {NAME,IMAGE1,PRESENT_PRICE}  = goods;
               // 不存在   直接封装成一个商品 添加大购物车中
               const newGoods = new Goods(id,NAME,IMAGE1,PRESENT_PRICE)
            
               carts.unshift(newGoods)

               // 刷新购车车 
               $$.setCookie("cart",JSON.stringify(carts),1000 * 60 * 60 * 24)

           }
        
           // 添加好的数据跳转到购物车页面 
           location.href = "./cart.html"
        }

        class Goods {
            constructor(id,name,image,price) {
                 this.id = id;
                 this.name = name;
                 this.image = image;
                 this.price = price;
                 this.num = 1;
                 this.status = true;
            }
        }


    </script>
</body>

</html>